package com.example.shengyin.frontController;

import com.alibaba.fastjson2.JSON;
import com.example.shengyin.entity.*;
import com.example.shengyin.service.SurveyQuesService;
import com.example.shengyin.service.SurveyService;
import com.example.shengyin.service.SymService;
import com.example.shengyin.util.Result;
import com.example.shengyin.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * AdminController
 * 
 * @author ruoyi
 * @date 2023-07-29
 */
@RestController
@RequestMapping("/front/survey")
@Validated
@CrossOrigin(origins = "*", maxAge = 3600,allowCredentials="true")
//swagger

@Api(tags = "FrontSurveyController", description = "问卷调查类")
public class FrontSurveyController
{
    @Autowired
    private SurveyService service;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SurveyQuesService surveyQuesService;
    @ApiOperation("详细的信息，必须先登录和是这个问卷的参与者")
    @GetMapping(value = "/detail/{id}")
    public Result select(@PathVariable(value = "id") Long id, HttpServletRequest request)
    {
        String authorization = request.getHeader("Authorization");
        if(authorization==null)
            return Result.error("请先登录");
        User admin = (User) redisTemplate.opsForValue().get(authorization);
        if(admin==null)
            return Result.error("请先登录");
        List<Survey> selectus = service.selectus(admin.getId());
        Survey select = service.select(id);
        if(select==null)
            return Result.error("没有找到数据");
        if(select.getUserid()!=admin.getId())
            return Result.error("您不是这个问卷的参与者");
        return Result.success(select);
    }
    @ApiOperation("查找自己的所有调查问卷，必须先登录")
    @GetMapping(value = "/selectMine")
    public Result selectus(HttpServletRequest request)
    {
        System.out.println(request.getHeader("Authorization"));
        String authorization = request.getHeader("Authorization");
        if(authorization==null)
            return Result.error("请先登录");
        User admin = (User) redisTemplate.opsForValue().get(authorization);
        if(admin==null)
            return Result.error("请先登录");
        List<Survey> selectus = service.selectus(admin.getId());
        if(selectus==null)
            return Result.error("没有找到数据");
        return Result.success(selectus);
    }

    @ApiOperation("获得一份问卷，必须先登录，类别对应的是服务群体里的大类:1.儿童言语发展 2.儿童言语服务 3.成人言语服务,填数字即可,不填也可以，即所有类型的题目都可以")
    @PostMapping("/getSurvey")
    public Result insert(@ApiParam(name = "stype",value = "类别") @RequestParam(required = false) Long stype, @ApiParam(name = "number",value = "数目") @RequestParam(required = true) int number, HttpServletRequest request)
    {
        Survey survey=new Survey();
        System.out.println(request.getHeader("Authorization"));
        if(request.getHeader("Authorization")==null)
            return Result.error("请先登录");
        User user = (User) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(user==null)
            return Result.error("请先登录");
        survey.setPhone(user.getPhone());
        survey.setUserid(user.getId());
        if(number<=0)
            return Result.error("题目的数量不能小于0");
        List<Long> list = surveyQuesService.listid(stype);
        if(number>list.size())
            return Result.error("题目的数量不够");
        Collections.shuffle(list);
        Collections.shuffle(list);
        Collections.shuffle(list);
        List<Long> longs = list.subList(0, number);
        Collections.sort(longs);
        System.out.println(JSON.toJSONString(longs));
        String ids= StrUtil.ArreyListtoString(longs);
        List<SurveyQues> listsome = surveyQuesService.listsome(stype, ids);
        survey.setChoseques(ids);
        survey.setStype(stype);
        int insert = service.insert(survey);
        Long selectid = service.selectid(user.getPhone());
        if(insert==0)
            return Result.error("添加失败");
        Map map=new HashMap<>();
        map.put("data",listsome);
        map.put("id",selectid);
        return Result.success(map,"添加成功");
    }

    @ApiOperation("返回问卷答案,答案的类型是1,2,3,4这样的以逗号隔开的数据")
    @PostMapping("/anwser")
    public Result anwser(@ApiParam(name = "id",value = "编号") @RequestParam(required = true) Long id, @ApiParam(name = "ids",value = "答案") @RequestParam(required = true) String ids, HttpServletRequest request)
    {
        Survey survey=new Survey();
        String authorization = request.getHeader("Authorization");

        String[] split = ids.split(",");
        Survey select = service.select(id);
        System.out.println(request.getHeader("Authorization"));
        if(request.getHeader("Authorization")==null)
            return Result.error("请先登录");
        User user = (User) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(user==null)
            return Result.error("请先登录");
        if(user.getId()!=select.getUserid()&&user.getPhone().equals(select.getPhone()))
            return Result.error("您不是该问卷的参与者，无法操作");

        survey.setPhone(select.getPhone());
        survey.setUserid(select.getUserid());

        List<SurveyQues> listsome = surveyQuesService.listsome(select.getStype(),select.getChoseques());
        int m=0;
        for (int i = 0; i < split.length; i++) {
            if(split[i].equals("1"))
                m=m+listsome.get(i).getOpvalue1();
            if(split[i].equals("2"))
                m=m+listsome.get(i).getOpvalue2();
            if(split[i].equals("3"))
                m=m+listsome.get(i).getOpvalue3();
            if(split[i].equals("4"))
                m=m+listsome.get(i).getOpvalue4();
            System.out.println(i+":"+m);
        }
        select.setChoseanswer(ids);
        select.setScore((short)m);
        select.setFinishtime(new Date());
        int update = service.update(select);
        if(update!=0)
            return Result.success(select,"提交成功");
        return Result.error("提交失败");



    }


    @ApiOperation("查看自己的问卷，必须先登录")
    @GetMapping("/preview/{id}")
    public Result preview(@PathVariable(value = "id") Long id,HttpServletRequest request)
    {
        System.out.println("id:"+id);
        Survey select = service.select(id);
        if(select==null)
            return Result.success("没有数据");
        System.out.println(request.getHeader("Authorization"));
        if(request.getHeader("Authorization")==null)
            return Result.error("请先登录");
        User user = (User) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(user==null)
            return Result.error("请先登录");
        if(user.getId()!=select.getUserid()&&user.getPhone().equals(select.getPhone()))
            return Result.error("您不是该问卷的参与者，无法操作");
        List<SurveyQues> getlist = surveyQuesService.getlist(select.getChoseques());
        System.out.println("getlist"+JSON.toJSONString(getlist));
        String chose = select.getChoseanswer();
        if(chose!=null)
        {
            String[] split = chose.split(",");
            for (int i = 0; i < split.length; i++) {
                getlist.get(i).setChoice(split[i]);
            }
        }
        select.setQues(getlist);
        System.out.println("Result"+JSON.toJSONString(select));
        return Result.success(select);
    }




}
